package com.fengye.algorithms.leecode;

import com.fengye.algorithms.leecode.common.ListNode;

/**
 * @Author fengye
 * @Date 2023/4/8 10:02
 **/
public class RemoveNthFromEnd19 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head == null || (head.next == null && n == 1)) {
            return null;
        }

        ListNode slow = head;
        ListNode fast = head;
        int c = 0;
        while(fast.next != null) {
            if(c >= n) {
                slow = slow.next;
            }
            fast = fast.next;
            c++;
        }
        if((c+1) == n) {
            head = head.next;
            slow.next = null;
        } else if(n==1){
            slow.next = null;
        } else {
            ListNode temp = slow.next;
            slow.next = temp.next;
            temp.next = null;
        }
        return head;
    }
}
